<template>
  <div class="app-container">

    <header>
      <el-row>
        <el-col :span="12">
        <h3>CodeLabs</h3>
        </el-col>
          <el-col :span="12">
      <el-dropdown
              @command="handleCommand"
              v-if="loginStoreAble"
              class="fr"
      >
        <el-button type="primary">
          <span class="email">{{ storeinfo.email }}</span>
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item disabled>账号信息</el-dropdown-item>
          <el-dropdown-item disabled>文档</el-dropdown-item>
          <el-dropdown-item command="logout">退出登入</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button
              @click="storeDialogVisible = true"
              v-else
              class="fr"
              type="primary"
      >登录应用市场
      </el-button>
        </el-col>
      </el-row>
    </header>
    <el-divider></el-divider>
    <el-row>
      <el-col :span="8">
        <div class="grid-content">
          <el-card shadow="never">
            <div slot="header">
              <span>模板</span>

              <el-dropdown @command="handleCardCommand" style="float: right; padding: 3px 0">
            <span class="el-dropdown-link">
               <i class="el-icon-more el-icon--right"></i>
            </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="d" >配置卡片</el-dropdown-item>
                  <el-dropdown-item command="e" divided>移除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <i class="el-icon-refresh" style="float: right; padding: 3px 0"></i>
            </div>
            <templates v-bind:latestCode="latestCode" v-bind:templateOptions="template_options" :template-tag.sync="templateTag" :template-name.sync="templateName"></templates>

          </el-card>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content">
          <el-card shadow="never">
            <div slot="header">
              <span>数据结构</span>

              <el-dropdown @command="handleCardCommand" style="float: right; padding: 3px 0">
            <span class="el-dropdown-link">
               <i class="el-icon-more el-icon--right"></i>
            </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="d" >配置卡片</el-dropdown-item>
                  <el-dropdown-item command="e" divided>移除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

              <i class="el-icon-refresh" style="float: right; padding: 3px 0"></i>
            </div>
          <dataStructure v-bind:latestCode="latestCode" v-bind:moduleList="moduleList"></dataStructure>

          </el-card>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content">
          <el-card shadow="never">
            <div slot="header">
              <span>算法</span>

              <el-dropdown @command="handleCardCommand" style="float: right; padding: 3px 0">
            <span class="el-dropdown-link">
               <i class="el-icon-more el-icon--right"></i>
            </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="d" >配置卡片</el-dropdown-item>
                  <el-dropdown-item command="e" divided>移除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

              <i class="el-icon-refresh" style="float: right; padding: 3px 0"></i>
            </div>
            <algorithm v-bind:latestCode="latestCode" v-bind:commandOptions="command_options"></algorithm>

          </el-card>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <div class="grid-content">
          <el-card shadow="never">
            <div slot="header">
              <span>模板配置</span>

              <el-dropdown @command="handleCardCommand" style="float: right; padding: 3px 0">
            <span class="el-dropdown-link">
               <i class="el-icon-more el-icon--right"></i>
            </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="d" >配置卡片</el-dropdown-item>
                  <el-dropdown-item command="e" divided>移除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

              <i class="el-icon-refresh" style="float: right; padding: 3px 0"></i>
            </div>
            <templateConfig v-bind:latestCode="latestCode" v-bind:templateOptions="template_options" :template-tag.sync="templateTag" :template-name.sync="templateName"></templateConfig>

          </el-card>
        </div>
      </el-col>
    </el-row>


    <el-divider></el-divider>

    <el-button type="primary" @click="handleGenerate">代码生成</el-button>
    <el-button type="primary" @click="handleCopy">复制</el-button>
    <el-button type="primary" @click="handleShare">分享</el-button>
    <el-button type="primary" class="fr" @click="handleCodelabsSave">保存</el-button>
    <el-button type="primary" class="fr" @click="handleOutputConfig">输出设置</el-button>
    <!----------------------------------- 输出设置 ---------------------------------------------->
    <el-drawer title="输出设置" :before-close="handleClose" :visible.sync="drawerVisible" direction="rtl" custom-class="demo-drawer" ref="drawer" size="60%">
      <div class="demo-drawer__content">
        <el-alert
                title="如不设置前端项目根目录，则生成的代码文件默认保存至后端项目模块下的views目录"
                type="error">
        </el-alert>
        <el-form :model="outputConfig">
          <el-form-item label="项目根目录" :label-width="formLabelWidth">
            <el-input v-model="outputConfig.project_dir" placeholder="windows系统目录格式 D:\uctoo,linux系统目录格式 /home/uctoo" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="保存至模块" :label-width="formLabelWidth">
            <el-select v-model="outputConfig.module" allow-create filterable placeholder="请选择模块名称" clearable>
              <el-option
                    v-for="item in moduleList"
                    :key="item.alias"
                    :label="item.name"
                    :value="item.alias">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="模块下路径" :label-width="formLabelWidth">
            <el-input v-model="outputConfig.path" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="保存文件名" :label-width="formLabelWidth">
            <el-input v-model="outputConfig.filename" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="$refs.drawer.closeDrawer()" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>
    <el-row>
      <el-col :span="24">
        <div class="grid-content">
          <el-card shadow="never">
            <div slot="header">
              <span>生成代码</span>

              <el-dropdown @command="handleCardCommand" style="float: right; padding: 3px 0">
            <span class="el-dropdown-link">
               <i class="el-icon-more el-icon--right"></i>
            </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="d" >配置卡片</el-dropdown-item>
                  <el-dropdown-item command="e" divided>移除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

              <i class="el-icon-refresh" style="float: right; padding: 3px 0"></i>
            </div>
            <el-input
                    type="textarea"
                    autosize
                    placeholder="生成代码结果"
                    v-model="preview_content">
            </el-input>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <el-dialog
            title="登录应用市场"
            :visible.sync="storeDialogVisible"
            width="20%"
            center
            @close="closeDialog"
    >
      <el-row>
        <el-col>
          <el-alert title="请使用www.uctoo.com的帐号登录" type="info" show-icon>
          </el-alert>
        </el-col>
      </el-row>
      <el-row style="margin-top:10px">
        <el-col>
          <el-form
                  :rules="storeFormRules"
                  label-position="top"
                  label-width="80px"
                  :model="storeForm"
                  ref="storeFormRef"
          >
            <el-form-item prop="email">
              <el-input
                      prefix-icon="el-icon-user"
                      ref="email"
                      v-model="storeForm.email"
                      placeholder="请输入邮箱"
                      name="email"
                      type="text"
                      tabindex="1"
                      autocomplete="on"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                      prefix-icon="el-icon-lock"
                      ref="password"
                      show-password
                      type="password"
                      v-model="storeForm.password"
                      placeholder="请输入密码"
                      name="password"
                      tabindex="2"
                      autocomplete="on"
                      @keyup.native="checkCapslock"
                      @blur="capsTooltip = false"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleStoreForm"
              >登录</el-button
              >
              <el-button
                      @click="
                  () => {
                    this.$refs.storeFormRef.resetFields();
                  }
                "
              >重置</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import 'highlight.js/styles/atom-one-dark.css'
import { mapGetters, mapActions } from "vuex";
import dataStructure from './component/dataStructure'
import templates from './component/templates'
import algorithm from './component/algorithm'
import templateConfig from './component/templateConfig'
import { loginStore } from "@/api/user";

export default {
  components: {
    dataStructure,
    templates,
    algorithm,
    templateConfig
  },
  name: 'develop_codelabsindex',
  data() {
    return {
      title: 'CodeLabs',
      formLabelWidth: '120px',
      moduleCreateVisible: false,
      latestCode : {},
      template_options: [],
      command_options: [],
      // 预览内容
      preview_content: '',
      drawerVisible: false,
      // rule
      rules: {
        module: [
          { required: true, message: '请输入模块名称', trigger: 'blur' }
        ]
      },
      outputConfig: {
        project_dir:'',module:'',path:'',filename:'',
      },
      moduleList:'',
      loading: false,
      timer: null,
      loginStatus: false,
      storeDialogVisible: false,
      storeForm: {},
      capsTooltip: false,
      storeFormRules: {
            email: [{ required: true, type: "email", trigger: "blur" }],
            password: [{ required: true, trigger: "blur" }]
      },
      templateTag:'template',
      templateName:''
    }
  },
  computed: {
    ...mapGetters(["storeinfo"]),
    loginStoreAble() {
      return this.storeinfo && this.storeinfo.remember_token ? true : false;
    }
  },
  mounted() {
    let { email, remember_token } = this.storeinfo;
    let authdata = { email, appstore_user_token: "Bearer" + remember_token };
    let params = {id: ''};
    if(this.$route.query.id){
      params = {id: this.$route.query.id};
    }
    this.$http.get("codelabsLatest",{ params:params}).then(response => {
      this.latestCode = response.data;
    });
    this.$http.get("codelabsTemplates",{ params: authdata }).then(response => {
      this.template_options= response.data;
    });
    this.$http.get("codelabsAlgorithm",{ params: authdata }).then(response => {
      this.command_options= response.data;
    });
    this.$http.get("modules").then(response => {  //接口返回全量数据
      this.moduleList = response.data;
    });
  },
  methods: {
    ...mapActions({
      loginStore: "user/loginStore",
      logoutStore: "user/logoutStore"
    }),
    handleGenerate() {
          var submitData = {id:this.latestCode.id}
          this.$http.post('codelabsGenerate', submitData).then(response => {
            this.preview_content = response.data
            if (response.code === 10000) {
              this.$message.success(response.message)
            } else {
              this.$message.error(response.message)
            }
          })
    },
    handleCardCommand(command) {
      this.$message('click on item ' + command);
    },
    handleCopy() {
      this.$message('click on handleCopy ');
    },
    handleShare() {
      let { email, remember_token } = this.storeinfo;
      let submitData = {id:this.latestCode.id,email, appstore_user_token: "Bearer" + remember_token}
      if(this.latestCode.id){
        this.$http.post('codelabsShare', submitData).then(response => {
          this.$message.success(response.message)
        })
      }
    },
    handleCodelabsSave() {
      let submitData = {id:this.latestCode.id,result:this.preview_content}
      if(this.latestCode.id){
        this.$http.put('codelabsSavefile/'+this.latestCode.id, submitData).then(response => {
          this.$message.success(response.message)
        })
      }
    },
    handleOutputConfig() {
      let params = {id: ''};
      if(this.$route.query.id){
        params = {id: this.$route.query.id};
      }
      this.$http.get("codelabsLatest",{ params:params}).then(response => {
        this.latestCode = response.data;
        let {project_dir,module,path,filename} = JSON.parse(this.latestCode.output);
        this.outputConfig.project_dir = project_dir||'';
        this.outputConfig.module = module||'';
        this.outputConfig.path = path||'';
        this.outputConfig.filename = filename||'';
      });
      this.drawerVisible = true
    },
    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.$confirm('确定要提交表单吗？')
              .then(_ => {
                this.loading = true;
                let submitData = {id:this.latestCode.id,output:JSON.stringify(this.outputConfig)}
                if(this.latestCode.id){
                  this.$http.put('codelabs/'+this.latestCode.id, submitData).then(response => {
                    this.$message.success(response.message)
                  })
                }else{
                  this.$http.post('codelabs', submitData).then(response => {
                    this.latestCode.id = response.data
                    this.$message.success(response.message)
                  })
                }

                this.timer = setTimeout(() => {
                  done();
                  // 动画关闭需要一定的时间
                  setTimeout(() => {
                    this.loading = false;
                  }, 400);
                }, 2000);
              })
              .catch(_ => {});
    },
    cancelForm() {
      this.loading = false;
      this.drawerVisible = false;
      clearTimeout(this.timer);
    },
    handleStoreForm() {
      this.$refs.storeFormRef.validate(async valid => {
        if (valid) {
          let { code, data } = await loginStore(this.storeForm);
          if (code === 10000) {
            this.loginStore(data);
            this.storeDialogVisible = false;
          }
        }
      });
    },
    handleCommand(command) {
      this.logoutStore();
    },
    closeDialog() {
      this.$refs.storeFormRef.clearValidate();
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
  }
}

</script>

<style scoped>

</style>
